﻿
@using TD.CTS.Data.Entities
@model TD.CTS.Data.Entities.Schedule

@section head{
    <link href="@Url.Content("~/Content/td/td.kendo.grid.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/td/td.kendo.tabstrip.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/td/td.kendo.grid.js")"></script>

    <style type="text/css">
        .td-textarea-edit {
            width: 300px !important;
            height: 60px !important;
        }
         #ProceduresGrid tr td {
        border-width: 0 0 1px 1px;
    }
    </style>
}
@{
    //var isNew = ViewBag.IsNew;
    //var buttonsRow = new System.Text.StringBuilder(@"<tr class='k-filter-row'><th/><th style='text-align:right;'><a class='k-button k-button-icontext k-grid-add td-grid-button' title='Добавить визит' href='javascript: void(0)'><span class='k-icon k-add td-grid-button-image'></span></a></th>");
}

@Html.Partial("EditorTemplates/MainEditor")@RenderFooter()

@*@Html.RenderPartial(@Html.Partial("EditorTemplates/ScheduleDetailEditor", Model))*@
@(Html.Kendo().Window().Name("ProcedureEmployeeWindow").Width(700).Height(450).Draggable().Resizable(e=>e.Enabled(false)).Title("Сотрудники").Content(@<text>@Html.Partial("EditorTemplates/ProcedureEmployeeEditor", Model)</text>).Visible(false).Modal(true)/*.HtmlAttributes(new { @class = "k-popup-edit-form" })*/)

@*@(Html.Kendo().Window().Name("PatientsWindow").Width(700).Height(450).Draggable().Resizable(e => e.Enabled(false)).Title("Сотрудники").Content(@<text>@Html.Partial("EditorTemplates/AddPatient", new Patient())</text>).Visible(false).Modal(true)/*.HtmlAttributes(new { @class = "k-popup-edit-form" })*/)*@
@*@(Html.Kendo().Window().Name("VisitRoleEmployeeWindow").Width(700).Height(400).Draggable().Resizable().Title("Сотрудники для визита ").Content(@<text>@Html.Partial("EditorTemplates/VisitRoleEmployeeEditor", Model)</text>).Visible(false).Modal(true))*@

@helper RenderFooter()
{
    @(Html.Kendo().TabStrip()
    .Name("VisitsStrip")
    .Events(events => events.Show("ShowTab"))
    .Animation(false)
    .Items(visittabs =>
    {
        visittabs.Add()
            .Text("Краткая информация")
            .Selected(true)
            .Content(@<text>@Html.Partial("EditorTemplates/ScheduleVisitEditor", Model)</text>);
        visittabs.Add()
            .Text("Сотрудники")
            .Selected(false)
            .Content(@<text>@Html.Partial("EditorTemplates/ScheduleEmployeeEditor", Model)</text>);
        visittabs.Add()
            .Text("Подробная информация")
            .Selected(false)
            .ContentHtmlAttributes(new {style = "padding:0;"})
            .LoadContentFrom("GetScheduleDetailContent", "Schedules", new { ScheduleID = Model.Id });
           // .Content(@<text>@Html.Partial("EditorTemplates/ScheduleDetailEditor", Model)</text>);



    })
)
}



<script>
    var validator = $("#scheduleForm").kendoValidator().data("kendoValidator");
    /*--------------------------------Расписание------------------------------------------------------------*/

    function SaveSchedule() {
        if (validator.validate()) {
            $.ajax({
                type: "POST",
                url: "@Url.Action("UpdateSchedule", "Schedules")",
                data: {
                    "Id": $("#Id").val(),
                    //"BeginDate": $("#BeginDate").val(),
                    //"BeginDate": $("#BeginDate").data("kendoDatePicker").value().toISOString(),
                    "PatientCode": $("#PatientCode").val(),
                    "TrialCenterID": $("#TrialCenterID").val(),
                    "ScheduleStatus": $("#ScheduleStatus").val(),
                    //"TrialCode": $("#TrialCode").val(),
                    "Comment": $("#Comment").val(),
                    "RandN": $("#RandN").val(),
                    "ScrN": $("#ScrN").val()
                },
                success: function(result) {
                    kendo_grid_reload($("#VisitsGrid"));
                    var saveNotification = $("#SaveNotification").data("kendoNotification");
                    saveNotification.show("Сохранено", "success");
                },
                error: AjaxError
            });
        }
    }

    //функция пересчета запланированных дат в рассписании

    @*function CalcSchedule() {
        if (confirm("Заполнить расписание?")) {
            $.ajax({
                type: "POST",
                url: "@Url.Action("CalcSchedule", "Schedules")",
                data: { "Id": @Model.Id},
                success: function (result) {
                    kendo_grid_reload($("#VisitsGrid"));
                    $('#VisitsStrip').data().kendoTabStrip.reload($('#VisitsStrip .k-item:nth-child(3)'));
                    $("#SaveNotification").data("kendoNotification").show("Выполнено", "success");
            },
            error: AjaxError
            });
        }
    }*@
    //функция пересчета запланированных дат в рассписании начиная с указанного визита
    function CalcVisitButtonClick(ScheduleVisitId) {
        if (confirm("Пересчетать плановые даты последующих визитов от данного визита ?")) {
            $.ajax({
                type: "POST",
                url: "@Url.Action("CalcScheduleByVisit", "Schedules")",
                data: { "Id": ScheduleVisitId},
            success: function (result) {
                kendo_grid_reload($("#VisitsGrid"));
                $('#VisitsStrip').data().kendoTabStrip.reload($('#VisitsStrip .k-item:nth-child(3)'));
                $("#SaveNotification").data("kendoNotification").show("Выполнено", "success");
            },
            error: AjaxError
        });
    }
        }



//------------------------------Визиты-----------------------------------------------------------------------

    //var validatorRules = {
    //    rules: {
    //        // This rule is executed when leaving a cell but the return value of false doesn't display any error message or prevent leaving the cell
    //        customRule1: function (input) {
    //            // OpCode must not be empty
    //            if (input.attr("name") == "ScheduleDate") {
    //                return $.trim(input.val()) !== "" && !$('#Canceled')[0].checked;
    //            }
    //            return true;
    //        }
    //    },
    //    messages: {
    //        customRule1: "All fields are required"
    //    }
    //};


    //Изменение визита
    function OnVisitsEdit(e) {
        var datePickerInRow = $(e.container).find('#ScheduleDate').data("kendoDatePicker");
        //datePickerInRow.min(e.model.MinDate);
        //datePickerInRow.max(e.model.MaxDate);
        //Вызываем базовое редактирование
        kendo_grid_onrowedit(e);
    }
    //Окончание действия над визитом
    function VisitsRequestEnd(e) {
        if(e.type === "update" || e.type === "destroy")
        {
            //перечитываем грид с сервера при обновлении и удалении
            $('#VisitsStrip').data().kendoTabStrip.reload($('#VisitsStrip .k-item:nth-child(3)'));
            //после удаления обновляем грид
            if(e.type === "destroy")
            {
                kendo_grid_reload($("#VisitsGrid"));
            }
        }
    }

    //Ошибка в визите
    function OnVisitsError(e) {
        if (e.errors && e.status == 'customerror') {
            var grid = $('#VisitsGrid').data('kendoGrid');
            var gridElement = grid.editable.element;
            var validationMessageTemplate = kendo.template(
                "<div id='#=field#_validationMessage' " +
                    "class='k-widget k-tooltip k-tooltip-validation " +
                    "k-invalid-msg field-validation-error' " +
                    "style='margin: 0.5em;' data-for='#=field#' " +
                    "data-val-msg-for='#=field#' role='alert'>" +
                    "<span class='k-icon k-warning'></span>" +
                    "#=message#" +
                    "<div class='k-callout k-callout-n'></div>" +
                    "</div>");

            $.each(e.errors, function(key, value) {
                if (value.errors) {
                    gridElement.find("[data-valmsg-for=" + key + "],[data-val-msg-for=" + key + "]")
                        .replaceWith(validationMessageTemplate({ field: key, message: value.errors[0] }));
                    gridElement.find("input[name=" + key + "]").focus();
                }
            });
            grid.one("dataBinding", function(e) {
                e.preventDefault(); // cancel grid rebind
            });
        } else {
            kendo_grid_error_handler(e);
        }
        //
        //var datePickerInRow = $(e.container).find('#ScheduleDate').data("kendoDatePicker");
        //datePickerInRow.min(e.model.MinDate);
        //datePickerInRow.max(e.model.MaxDate);
        //Вызываем базовое редактирование
        //kendo_grid_onrowedit(e);
    }
    //-------------------------Сотрудники по умолчанию-----------------------------------------------------------------------------------------------------
    function EmployeesRequestEnd(e) {
        if(e.type === "destroy" || e.type ==="update")
            {
                kendo_grid_reload($("#EmployeeGrid"));
            }
    }
    //Прячем кнопку удаления
    function OnEmployeeGridDataBound() {
        //Selects all delete buttons
        $("#EmployeeGrid tbody tr .k-grid-delete").each(function () {

            var currentDataItem = $("#EmployeeGrid").data("kendoGrid").dataItem($(this).closest("tr"));
            //Check in the current dataItem if the row is deletable
            if (currentDataItem.Id == null) {
                $(this).remove();
            }

        });
    }
    //------------------------Сотрудники для визита (Не используется)--------------------------------------------------------------------------------------
    function OpenVisitRoleEmployeeWindow(scheduleVisitId,scheduleVisitName) {
        var windowJs = $("#VisitRoleEmployeeWindow");
        var windowK = windowJs.data("kendoWindow");
        windowK.title('Изменение ролей сотрудников для визита '+scheduleVisitName);
        windowK.center().open();
        windowJs.find("input:hidden#VisitRoleEmployeeWindow_VisitId").val(scheduleVisitId);
        //var filter = { ScheduleVisitID :17};
        kendo_grid_reload($("#VisitRoleEmployeeGrid"));

    }
    //----------------------Сотрудники в процедурах визита (ProcedureEmployee)------------------------------------------------------------------------------------------------------------------
    function OpenProceduereEmployeeWindow(trialvisitid,procedurecode) {
        var grid = $("#ProcedureEmployeesEditorGrid");
        var window = $("#ProcedureEmployeeWindow");
        window.data("kendoWindow").center().open();
        var filter = {
            //ScheduleID :17,
            TrialVisitID:trialvisitid,
            ProcedureCode:procedurecode,
            //TrialVersionNo :1//,
            //SystemRoleCode:'DO',
            //TrialCenterID :2
        };
        //Растягиваем грид в размер окна
        StretchGrid(window,grid);
        //Обновляем грид в зависимости от выбранного визита и процедуры
        kendo_grid_reload(grid,filter);
    }
    //-------------------------------------------------------------------------------------------------------------------------------------------------------------------


    $(document).ready(function () {
        SetContentBlock($("#VisitsStrip .k-content"));
        kendo_grid_init($("#ProcedureEmployeesEditorGrid"));
        //StretchGrid($("#VisitRoleEmployeeWindow"),$("#VisitRoleEmployeeGrid"))

        kendo_grid_init($("#VisitsGrid"));
        //$("#VisitsGrid").kendoValidator(validatorRules);
        $(window).bind("resize", function () {
            var tabStrip = $("#VisitsStrip").data("kendoTabStrip");
            var tab = tabStrip.select();
            var index = tab.index();
            var conteiner = tabStrip.contentElements[index];
            StretchGrid($(conteiner), $(conteiner.firstElementChild));
        });


        //var input = $('<input type=\"checkbox\" class=\"k-checkbox\" style=\"margin:0; \" />').val(1);
        var createUrl = $('@Html.ActionLink(" ", "Create", "Schedules", null, new { @style = "float:right;", @class = "k-button k-button-icontext td-grid-button", title = "Создать новое расписание" })');
        var span = $('<span class=\"k-add k-icon td-grid-button-image\">Создать</span>');
        createUrl.append(span);

        //var input = $('<a style=\"float:right;\" class=\"k-button k-button-icontext td-grid-button\" href=\"/Schedules/Create\" title=\"Создать новое расписание\"><span class=\"k-add k-icon td-grid-button-image\">Создать</span></a>');
        $('div.k-header.td-pagetitle').append(createUrl);
        

        //var windowJs = $("#PatientsWindow");
        //var windowK = windowJs.data("kendoWindow");
        //windowK.title('Создание пациента');
        //windowK.center().open();

    });

    function ShowTab(e) {
        StretchGrid($(e.contentElement), $(e.contentElement.firstElementChild));
    }

    //------------------------Дополнительные функции---------------------------------------
    String.format = function() {
        // The string containing the format items (e.g. "{0}")
        // will and always has to be the first argument.
        var theString = arguments[0];

        // start with the second argument (i = 1)
        for (var i = 1; i < arguments.length; i++) {
            // "gm" = RegEx options for Global search (more than one instance)
            // and for Multiline search
            var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
            theString = theString.replace(regEx, arguments[i]);
        }

        return theString;
    };


</script>